import axios from 'axios';
import { showErrorMessage } from '@/utils/message';
import router from '@/router';
import { refreshToken } from '@/service/user/userService';
import { ElMessage } from 'element-plus';
import { redirectToUserLogin } from '@/router/instuction';
const api = axios.create({
    baseURL: '/api',
    timeout: 10000,
});
// 请求拦截器
api.interceptors.request.use(
    (config) => {
        // token校验
        const token = localStorage.getItem('accessToken');
        if (token!=undefined) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
// 响应拦截器
api.interceptors.response.use(
    response => {
        return response;
    },
    async error => {
        const originalRequest = error.config;
        // token失效处理
        if (error.response.status === 401 && !originalRequest._retry) {
            console.log("Token失效")
            originalRequest._retry = true;
            const reToken = localStorage.getItem('refreshToken');
            if (reToken) {
                try {
                    const response = await refreshToken(reToken as string); // 非空断言
                    console.log(response)
                    if (response.status == 200) {
                        localStorage.removeItem("accessToken");

                        const newAccessToken = response.data;
                        console.log(newAccessToken);
                        localStorage.setItem('accessToken', newAccessToken);
                        return api(originalRequest);
                    }else if(response.status==401){
                        redirectToUserLogin()
                    }
                } catch (refreshError) {
                    showErrorMessage('请先登录');
                    redirectToUserLogin()
                }
            } else {
                showErrorMessage('请先登录');
                window.location.href = '/user';
            }
        } else if (error.response) {
            // 其他错误处理
            switch (error.response.status) {
                case 400:
                    ElMessage.error('Bad request.');
                    break;
                case 404:
                    ElMessage.error('Resource not found.');
                    break;
                case 500:
                    ElMessage.error('Server error.');
                    break;
                default:
                    ElMessage.error(`Error: ${error.response.status}`);
            }
        } else {
            // Handle network or unknown errors not related to HTTP status codes
            ElMessage.error('Network or unknown error occurred.');
        }
        return Promise.reject(error);
    }
);


export default api;
